package com.ruoyi.lhky.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.lhky.mapper.TesterMapper;
import com.ruoyi.lhky.mapper.V0Mapper;
import com.ruoyi.lhky.pojo.StudyCompletion;
import com.ruoyi.lhky.pojo.Tester;
import com.ruoyi.lhky.pojo.V0;
import com.ruoyi.lhky.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class V0Service extends ServiceImpl<V0Mapper, V0> {

    @Autowired
    private TesterMapper testerMapper;

    @Autowired
    private V0Mapper v0Mapper;

    @Transactional
    public R saveOrUpdateV0Data(V0 v0) {
        // 插入V0数据
//        boolean result = save(v0);
//        if (!result) {
//            return new R(false, "新增失败");
//        }

        Long testerId = v0.getTesterId();

        V0 existingData = getOne(new QueryWrapper<V0>().eq("tester_id", testerId));

        if (existingData != null) {
            v0.setId(existingData.getId());
        }

        boolean result = saveOrUpdate(v0);


        // 查找对应的Tester
        Tester tester = testerMapper.selectById(v0.getTesterId());
        if (tester == null) {
            return new R(false, "未找到对应的受试者");
        }

        // 检查入选标准和排除标准
        boolean isExcluded = !v0.getInclOne() || !v0.getInclTwo() || !v0.getInclThree() ||
                !v0.getInclFour() || !v0.getInclFive() || v0.getStandOne() ||
                v0.getStandTwo() || v0.getStandThree() || v0.getStandFour() ||
                v0.getStandFive() || v0.getStandSix() || v0.getStandSeven() ||
                v0.getStandEight() || v0.getStandNine() || v0.getStandTen() ||
                v0.getStandElev();

        if (isExcluded) {
            tester.setGroupId(3);  // 设置为排除组
            testerMapper.updateById(tester);
            return new R(true, "该受试者被排除");
        }

        // 处理随机入组逻辑
//        if (v0.getRandomGroup() != null && v0.getRandomGroup()) {
//            tester.setRandom("true");
//            testerMapper.updateById(tester);
//        }

        return new R(result, result ? "保存成功" : "保存失败");
    }

    public V0 getV0ByTesterId(Long testerId){
        V0 v0 = v0Mapper.selectOne(new QueryWrapper<V0>().eq("tester_id", testerId));
        return v0;
    }

    public R updateTesterGroup(Long testerId, int randomResult) {
        boolean result = false;
        int info = testerMapper.updateGroupId(testerId, randomResult);
//        boolean result = saveOrUpdate(v0);
        if(info == 1 ) {
            result = true;
        }else if(info == 2){
            result = false;
        }
        return new R(result, result ? "保存成功" : "保存失败");
    }
}
